from PyQt6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton,
    QCheckBox,  QTextEdit,  QGridLayout, QGroupBox, QTableView, QHeaderView
)
from PyQt6.QtCore import Qt, pyqtSignal,  QAbstractTableModel, QModelIndex
from PyQt6.QtGui import  QPainter, QColor, QPen
import json
from config_manager import config_manager

class KeywordReplyTableModel(QAbstractTableModel):
    """关键词回复表格模型"""
    
    def __init__(self, data=None):
        super().__init__()
        self._data = data or [
            ("工作 工资 月薪", "年薪百万不是梦，我们这边有很多机会"),
            ("哪里 哪个 在哪", "我们在深圳这边上班，你呢")
        ]
        self._headers = ["关键词", "回复内容", "操作"]
    
    def rowCount(self, parent=None):
        return len(self._data)
    
    def columnCount(self, parent=None):
        return 3
    
    def data(self, index, role=Qt.ItemDataRole.DisplayRole):
        if role == Qt.ItemDataRole.DisplayRole:
            if index.column() < 2:
                return self._data[index.row()][index.column()]
            else:  # 操作列
                return "🗑️"
        return None
    
    def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole):
        if role == Qt.ItemDataRole.DisplayRole and orientation == Qt.Orientation.Horizontal:
            return self._headers[section]
        return None
    
    def add_row(self, keyword, reply):
        """添加新行"""
        self.beginInsertRows(QModelIndex(), len(self._data), len(self._data))
        self._data.append((keyword, reply))
        self.endInsertRows()
    
    def remove_row(self, row):
        """删除行"""
        if 0 <= row < len(self._data):
            self.beginRemoveRows(QModelIndex(), row, row)
            del self._data[row]
            self.endRemoveRows()


class ToggleSwitch(QWidget):
    """自定义滑动开关组件 - 紧凑版"""
    toggled = pyqtSignal(bool)
    
    def __init__(self, text="", checked=False, parent=None):
        super().__init__(parent)
        self.setFixedSize(40, 20)  # 更小的尺寸：40x20
        self._checked = checked
        self.text = text
        
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)
        
        # 背景轨道 - 更窄的轨道
        track_color = QColor("#007bff") if self._checked else QColor("#ccc")
        painter.setBrush(track_color)
        painter.setPen(Qt.PenStyle.NoPen)
        painter.drawRoundedRect(0, 3, 40, 14, 7, 7)  # 轨道：40x14，圆角7
        
        # 滑块 - 更小的滑块
        knob_x = 24 if self._checked else 2  # 滑块移动范围：2到24
        painter.setBrush(QColor("white"))
        painter.setPen(QPen(QColor("#ddd"), 1))
        painter.drawEllipse(knob_x, 1, 16, 16)  # 滑块：16x16圆形
        
    def mousePressEvent(self, event):
        if event.button() == Qt.MouseButton.LeftButton:
            self.toggle()
    
    def toggle(self):
        self._checked = not self._checked
        self.update()
        self.toggled.emit(self._checked)
    
    def isChecked(self):
        return self._checked
    
    def setChecked(self, checked):
        if self._checked != checked:
            self._checked = checked
            self.update()
            self.toggled.emit(self._checked)


class CommunicationWidget(QWidget):
    def __init__(self):
        super().__init__()
        # 存储所有UI字段的引用
        self.ui_fields = {}
        self.config_filename = "communication_config.json"  # 改为更明确的名称

        # 默认配置数据
        self.default_config = {
            "tableName": "gt",
            "changeWechat": True,
            "changePhone": False,
            "pass": {
                "age": "非常抱歉，您的年龄暂时不符合要求，祝您找到满意的工作",
                "sex": "",
                "xl": "",
                "filter": "打扰您了，祝您找到满意的工作！"
            },
            "speed": {
                "Start1": 5,
                "End1": 8,
                "Start2": 10,
                "End2": 12,
                "Start3": 10,
                "End3": 12
            },
            "zw": [],
            "keyword": [
                {
                    "key": "工价 工资 月薪 底薪 薪资 多少钱 待遇 五险一金",
                    "value": "详细的薪资待遇要根据经验来确认，我们微信上聊吧，这里回复的比较慢"
                },
                {
                    "key": "地址 地方 地点 位置 在哪里 在那里 定位 哪个区",
                    "value": "具体位置我微信上发你哈，咱们先加个微信，这里回复比较慢，不经常在线"
                },
                {
                    "key": "白班 夜班 晚班 两班倒",
                    "value": "咱们这个岗位都是朝九晚六，周末双休，不加班的哈，方便价格微信细聊么，这里不经常在线"
                },
                {
                    "key": "吃住  包吃 包住 住宿 宿舍",
                    "value": "目前没有这方面的补贴，咱们可以先加个微信细聊，这里不经常在线，回复比较慢"
                },
                {
                    "key": "餐补 车补 车费 路费",
                    "value": "目前没有这方面的补贴，其他福利咱们可以先加个微信细聊，这里不经常在线"
                },
                {
                    "key": "好",
                    "value": "好的"
                }
            ],
            "filterVirtual": True,
            "filterCompose": False,
            "timeClean": False,
            "noChat": False,
            "noChatText": "",
            "limitAge": True,
            "limitAgeText": {
                "start": "25",
                "end": "45"
            },
            "limitSex": True,
            "limitSexText": "男",
            "limitXl": False,
            "limitXlList": [
                "大专",
                "本科",
                "硕士"
            ],
            "filterPeople": True,
            "filterPeopleText": "不考虑 不感兴趣 不太合适 不太适合 不合适 不适合 不想了解 傻 举报 滚 烦人 骚扰 草 你妈 不符合",
            "random1": "这会咨询人太多了，要不交换一下微信！",
            "random2": "这会是招聘季，咨询人比较多，你先加我微信吧！",
            "random3": "加一下微信，我们微信沟通更方便！"
        }

        self.config_data = config_manager.load_config(self.config_filename, self.default_config)

        self.init_ui()
        # 初始化时加载配置数据
        self.load_config()
    
    def init_ui(self):
        """初始化沟通配置界面"""
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(15, 15, 15, 15)
        main_layout.setSpacing(10)
        
        # 标题和保存按钮
        header_layout = QHBoxLayout()
        
        title_label = QLabel("💬 沟通配置管理")
        title_label.setStyleSheet("""
            QLabel {
                font-size: 20px;
                font-weight: bold;
                color: black;
                background-color: white;
                border: none;
            }
        """)
        header_layout.addWidget(title_label)
        
        header_layout.addStretch()
        
        # 保存按钮
        save_btn = QPushButton("💾 保存配置")
        save_btn.setStyleSheet("""
            QPushButton {
                background-color: #007bff;
                color: white;
                border: none;
                padding: 8px 20px;
                border-radius: 4px;
                font-weight: bold;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #0056b3;
            }
            QPushButton:pressed {
                background-color: #004085;
            }
        """)
        # 连接保存按钮的点击事件
        save_btn.clicked.connect(self.save_config)
        header_layout.addWidget(save_btn)
        
        main_layout.addLayout(header_layout)
        
        # 直接使用主布局，不用滚动区域
        content_layout = QHBoxLayout()
        content_layout.setSpacing(15)

        # 左侧配置区域
        left_layout = QVBoxLayout()
        self.create_audience_filter(left_layout)
        self.create_auto_reply_settings(left_layout)
        content_layout.addLayout(left_layout)

        # 右侧配置区域
        right_layout = QVBoxLayout()
        self.create_filter_exchange(right_layout)
        self.create_random_first_sentence(right_layout)
        self.create_keyword_reply(right_layout)
        content_layout.addLayout(right_layout)

        # 直接添加到主布局，不用滚动区域
        main_layout.addLayout(content_layout)
    
    def create_audience_filter(self, parent_layout):
        """创建人群筛选区域"""
        group = QGroupBox("👥 人群筛选")
        group.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                color: black;
                background-color: white;
                border: 1px solid #ccc;
                border-radius: 6px;
                margin-top: 8px;
                padding-top: 8px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 5px 0 5px;
                color: black;
            }
        """)
        layout = QVBoxLayout(group)
        layout.setSpacing(8)
        
        # 年龄筛选 - 使用滑动开关
        age_layout = QHBoxLayout()
        
        age_label = QLabel("年龄限制")
        age_label.setStyleSheet("""
            QLabel {
                color: black;
                background-color: white;
                font-weight: 500;
                border: none;
            }
        """)
        age_layout.addWidget(age_label)
        
        age_switch = ToggleSwitch("年龄限制", False)
        self.ui_fields['age_enabled'] = age_switch
        age_layout.addWidget(age_switch)
        
        age_layout.addStretch()
        
        age_min = QLineEdit()
        age_min.setText("27")
        age_min.setMaximumWidth(50)
        age_min.setStyleSheet("""
            QLineEdit {
                background-color: white;
                color: black;
                border: 1px solid #ccc;
                padding: 2px;
                text-align: center;
            }
        """)
        self.ui_fields['age_min'] = age_min
        age_layout.addWidget(age_min)
        
        dash_label = QLabel("-")
        dash_label.setStyleSheet("color: black; background-color: transparent; border: none;")
        age_layout.addWidget(dash_label)
        
        age_max = QLineEdit()
        age_max.setText("45")
        age_max.setMaximumWidth(50)
        age_max.setStyleSheet("""
            QLineEdit {
                background-color: white;
                color: black;
                border: 1px solid #ccc;
                padding: 2px;
                text-align: center;
            }
        """)
        self.ui_fields['age_max'] = age_max
        age_layout.addWidget(age_max)
        
        age_unit = QLabel("岁")
        age_unit.setStyleSheet("color: black; background-color: white; border: none;")
        age_layout.addWidget(age_unit)
        layout.addLayout(age_layout)
        
        # 性别筛选 - 使用滑动开关
        gender_layout = QHBoxLayout()
        
        gender_label = QLabel("性别限制")
        gender_label.setStyleSheet("""
            QLabel {
                color: black;
                background-color: white;
                font-weight: 500;
                border: none;
            }
        """)
        gender_layout.addWidget(gender_label)
        
        gender_switch = ToggleSwitch("性别限制", True)
        self.ui_fields['gender_enabled'] = gender_switch
        gender_layout.addWidget(gender_switch)
        
        gender_layout.addStretch()
        
        male_cb = QCheckBox("男")
        female_cb = QCheckBox("女")
        male_cb.setChecked(True)
        female_cb.setChecked(True)

        checkbox_style = """
            QCheckBox {
                color: black;
                background-color: transparent;
                font-size: 12px;
                padding: 2px;
                spacing: 5px;  /* 添加文本和复选框间距 */
            }
            QCheckBox::indicator {
                width: 16px;
                height: 16px;
                border-radius: 3px;
                border: 1px solid #999;  /* 统一边框颜色 */
            }
            QCheckBox::indicator:unchecked {
                background-color: white;
            }
            QCheckBox::indicator:unchecked:hover {
                border: 1px solid #007bff;  /* 悬停时显示蓝色边框 */
                background-color: #f0f7ff;   /* 添加悬停背景色 */
            }
            QCheckBox::indicator:checked {
                background-color: #007bff;
                border: 1px solid #007bff;  /* 保持选中状态边框颜色一致 */
            }
            QCheckBox::indicator:checked:hover {
                background-color: #0066cc;   /* 悬停时深蓝色 */
            }
            QCheckBox:hover {
                color: #222;  /* 文本悬停效果 */
            }
        """

        male_cb.setStyleSheet(checkbox_style)
        female_cb.setStyleSheet(checkbox_style)
        
        self.ui_fields['gender_male'] = male_cb
        self.ui_fields['gender_female'] = female_cb
        
        gender_layout.addWidget(male_cb)
        gender_layout.addWidget(female_cb)
        layout.addLayout(gender_layout)
        
        # 学历筛选
        edu_main_layout = QHBoxLayout()
        
        # 左侧：标签和开关
        edu_left_layout = QVBoxLayout()
        
        edu_header_layout = QHBoxLayout()
        edu_label = QLabel("学历限制")
        edu_label.setStyleSheet("""
            QLabel {
                color: black;
                background-color: transparent;
                font-weight: 500;
                border: none;
            }
        """)
        edu_header_layout.addWidget(edu_label)
        
        edu_switch = ToggleSwitch("学历限制", True)
        self.ui_fields['education_enabled'] = edu_switch
        edu_header_layout.addWidget(edu_switch)
        edu_header_layout.addStretch()
        
        edu_left_layout.addLayout(edu_header_layout)
        edu_left_layout.addStretch()
        
        edu_main_layout.addLayout(edu_left_layout)
        
        # 右侧：学历选项
        edu_layout = QGridLayout()
        edu_layout.setSpacing(4)
        
        options = [
            ("初中及以下", False), ("中专/中技", False), ("大专", True),
            ("本科", True), ("硕士", False), ("博士", False), ("全日制", False)
        ]
        
        row, col = 0, 0
        for text, checked in options:
            cb = QCheckBox(text)
            cb.setChecked(checked)
            cb.setStyleSheet(checkbox_style)
            # 修复字段名映射
            field_mapping = {
                "初中及以下": "education_初中",
                "中专/中技": "education_中专_中技", 
                "大专": "education_大专",
                "本科": "education_本科",
                "硕士": "education_硕士",
                "博士": "education_博士",
                "全日制": "education_全日制"
            }
            field_name = field_mapping.get(text, f"education_{text}")
            self.ui_fields[field_name] = cb
            edu_layout.addWidget(cb, row, col)
            col += 1
            if col > 3:
                col = 0
                row += 1
        
        # 创建右侧容器
        edu_right_widget = QWidget()
        edu_right_widget.setLayout(edu_layout)
        
        edu_main_layout.addWidget(edu_right_widget)
        
        layout.addLayout(edu_main_layout)
        
        # 过滤人群 - 使用滑动开关
        filter_layout = QHBoxLayout()
        
        filter_label = QLabel("过滤关键词")
        filter_label.setStyleSheet("""
            QLabel {
                color: black;
                background-color: white;
                font-weight: 500;
                border: none;
            }
        """)
        filter_layout.addWidget(filter_label)
        
        filter_switch = ToggleSwitch("过滤关键词", True)
        self.ui_fields['filter_keywords_enabled'] = filter_switch
        filter_layout.addWidget(filter_switch)
        
        filter_input = QLineEdit("不考虑 不考虑结婚 不会结婚 不想")
        filter_input.setStyleSheet("""
            QLineEdit {
                background-color: white;
                color: black;
                border: 1px solid #ccc;
                padding: 4px;
            }
        """)
        self.ui_fields['filter_keywords'] = filter_input
        filter_layout.addWidget(filter_input)
        layout.addLayout(filter_layout)
        
        parent_layout.addWidget(group)
    
    def create_auto_reply_settings(self, parent_layout):
        """创建自动回复设置"""
        group = QGroupBox("🤖 自动回复设置")
        group.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                color: black;
                background-color: white;
                border: 1px solid #ccc;
                border-radius: 6px;
                margin-top: 8px;
                padding-top: 8px;
            }
            QGroupBox::title {
                color: black;
            }
        """)
        layout = QVBoxLayout(group)
        layout.setSpacing(8)
        
        # 设置选项
        settings = [
            ("年龄不符", "非常抱歉，您的年龄不符合我的要求，谢谢您的理解！"),
            ("性别不符", ""),
            ("学历不符", ""),
            ("过滤沟通", "对不起，我觉得我们不太合适，谢谢您的理解！")
        ]
        
        text_style = """
            QTextEdit {
                background-color: white;
                color: black;
                border: 1px solid #ccc;
                padding: 4px;
            }
        """
        
        for title, default_text in settings:
            setting_layout = QVBoxLayout()
            setting_layout.setSpacing(3)
            
            title_label = QLabel(title)
            title_label.setStyleSheet("""
                color: black; 
                background-color: white;
                font-weight: 500;
            """)
            setting_layout.addWidget(title_label)
            
            text_edit = QTextEdit()
            text_edit.setMaximumHeight(50)
            text_edit.setPlainText(default_text)
            text_edit.setStyleSheet(text_style)
            # 使用标题作为字段名
            field_name = f"auto_reply_{title.replace('不符', '').replace('沟通', '')}"
            self.ui_fields[field_name] = text_edit
            setting_layout.addWidget(text_edit)
            
            layout.addLayout(setting_layout)
        
        parent_layout.addWidget(group)
    
    def create_filter_exchange(self, parent_layout):
        """创建筛选与交换区域"""
        group = QGroupBox("🔄 筛选与交换")
        group.setFixedHeight(100)
        group.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                color: black;
                background-color: white;
                border: 1px solid #ccc;
                border-radius: 6px;
                margin-top: 4px;
                padding-top: 4px;
            }
            QGroupBox::title {
                color: black;
            }
        """)
        layout = QVBoxLayout(group)
        layout.setSpacing(2)
        layout.setContentsMargins(8, 4, 8, 4)
        
        # 开关选项 - 使用滑动开关
        # 所有开关选项 - 6个开关排成2行3列
        all_switches = [
            ("交换微信", True),
            ("交换手机", False),
            ("过滤虚拟号码", True),
            ("过滤同事已聊", False),
            ("定时释放内存", False),
            ("不沟通职位", False)
        ]
        
        switches_layout = QGridLayout()
        switches_layout.setSpacing(0)  # 减少整体间距
        switches_layout.setVerticalSpacing(-10)  # 更大的负值压缩行间距
        switches_layout.setHorizontalSpacing(5)  # 水平间距更小
        switches_layout.setContentsMargins(0, 0, 0, 0)  # 移除布局边距
        switches_layout.setRowStretch(0, 0)  # 第一行不拉伸
        switches_layout.setRowStretch(1, 0)  # 第二行不拉伸
        
        for i, (text, checked) in enumerate(all_switches):
            switch_layout = QHBoxLayout()
            switch_layout.setSpacing(0)  # 减少内部间距
            switch_layout.setContentsMargins(0, 0, 0, 0)  # 移除内边距
            label = QLabel(text)
            label.setFixedHeight(18)  # 固定标签高度
            label.setStyleSheet("""
                QLabel {
                    color: black;
                    background-color: white;
                    border: none;
                    font-weight: 500;
                    font-size: 12px;
                    min-width: 80px;
                }
            """)
            switch_layout.addWidget(label)
            
            toggle_switch = ToggleSwitch(text, checked)
            toggle_switch.setFixedHeight(18)
            # 使用文本作为字段名
            field_name = text.replace('交换', 'exchange_').replace('过滤', 'filter_').replace('定时', 'timer_').replace('不沟通', 'no_chat_')
            self.ui_fields[field_name] = toggle_switch
            switch_layout.addWidget(toggle_switch)
            
            # 特殊处理"不沟通职位"，添加输入框
            if text == "不沟通职位":
                timing_input = QLineEdit("25")
                timing_input.setMaximumWidth(45)  # 稍微减小输入框宽度
                timing_input.setStyleSheet("""
                    QLineEdit {
                        background-color: white;
                        color: black;
                        border: 1px solid #ccc;
                        padding: 2px;
                        font-size: 12px;
                    }
                """)
                self.ui_fields['no_chat_position_days'] = timing_input
                switch_layout.addWidget(timing_input)
                
            switch_layout.addStretch()
            # 创建容器widget
            switch_widget = QWidget()
            switch_widget.setLayout(switch_layout)
            switch_widget.setMaximumHeight(20)  # 进一步限制每个开关组件的最大高度
            switch_widget.setContentsMargins(0, 0, 0, 0)  # 移除widget边距
            # 2行3列布局
            switches_layout.addWidget(switch_widget, i // 3, i % 3)
        
        layout.addLayout(switches_layout)
        parent_layout.addWidget(group)
    
    def create_random_first_sentence(self, parent_layout):
        """创建随机第一句区域"""
        group = QGroupBox("🎲 随机第一句")
        group.setFixedHeight(140)
        group.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                color: black;
                background-color: white;
                border: 1px solid #ccc;
                border-radius: 6px;
                margin-top: 8px;
                padding-top: 8px;
            }
            QGroupBox::title {
                color: black;
            }
        """)
        layout = QVBoxLayout(group)
        layout.setSpacing(5)
        
        # 预设问候语按钮
        greetings = [
            "你好，方便聊个微信，我想认识",
            "你好朋友，这边想和你聊个微信，了",
            "你好，想加你个微信，这里"
        ]
        
        button_style = """
            QLineEdit {
                background-color: white;
                color: black;
                border: 1px solid #ccc;
                border-radius: 4px;
                padding: 6px;
                text-align: left;
                font-size: 12px;
            }
            QLineEdit:hover {
                background-color: #f5f5f5;
                border: 1px solid #999;
            }
        """
        
        for i, greeting in enumerate(greetings, 1):
            btn = QLineEdit(greeting)
            btn.setStyleSheet(button_style)
            # 添加到ui_fields字典中
            self.ui_fields[f'random{i}'] = btn
            layout.addWidget(btn)
        
        parent_layout.addWidget(group)
    
    def create_keyword_reply(self, parent_layout):
        """创建关键词回复区域"""
        group = QGroupBox("🔑 关键词回复")
        group.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                color: black;
                background-color: white;
                border: 1px solid #ccc;
                border-radius: 6px;
                margin-top: 8px;
                padding-top: 8px;
            }
            QGroupBox::title {
                color: black;
            }
        """)
        layout = QVBoxLayout(group)
        layout.setSpacing(8)
        
        # 顶部输入行 - 关键词、回复内容、+ 按钮顶部对齐
        input_layout = QHBoxLayout()
        input_layout.setAlignment(Qt.AlignmentFlag.AlignTop)  # 顶部对齐
        
        keyword_input = QLineEdit()
        keyword_input.setPlaceholderText("关键词")
        keyword_input.setFixedWidth(120)  # 固定宽度
        keyword_input.setStyleSheet("""
            QLineEdit {
                background-color: white;
                color: black;
                border: 1px solid #ccc;
                padding: 4px;
            }
        """)
        self.ui_fields['new_keyword'] = keyword_input
        
        reply_input = QLineEdit()
        reply_input.setPlaceholderText("回复内容")
        reply_input.setStyleSheet("""
            QLineEdit {
                background-color: white;
                color: black;
                border: 1px solid #ccc;
                padding: 4px;
            }
        """)
        self.ui_fields['new_reply'] = reply_input
        
        add_btn = QPushButton("➕")
        add_btn.setFixedWidth(35)
        add_btn.setStyleSheet("""
            QPushButton {
                background-color: white;
                color: black;
                border: 1px solid #ccc;
                padding: 4px;
            }
            QPushButton:hover {
                background-color: #f5f5f5;
            }
        """)
        
        input_layout.addWidget(keyword_input)
        input_layout.addWidget(reply_input)
        input_layout.addWidget(add_btn)
        layout.addLayout(input_layout)
        
        # 创建QTableView
        table_view = QTableView()
        table_view.setMaximumHeight(200)  # 限制最大高度以启用滚动
        
        # 创建表格模型
        table_model = KeywordReplyTableModel()
        table_view.setModel(table_model)
        self.ui_fields['keyword_reply_table'] = table_model
        
        # 设置表格样式和行为
        table_view.setStyleSheet("""
            QTableView {
                background-color: white;
                color: black;
                border: 1px solid #dee2e6;
                gridline-color: #dee2e6;
                selection-background-color: #e7f3ff;
                selection-color: black;
            }
            QTableView::item {
                padding: 6px;
                border-bottom: 1px solid #dee2e6;
                color: black;
                background-color: white;
            }
            QTableView::item:selected {
                background-color: #e7f3ff;
                color: black;
            }
            QHeaderView::section {
                background-color: #f8f9fa;
                color: black;
                padding: 6px;
                border: 1px solid #dee2e6;
                font-weight: bold;
                font-size: 12px;
            }
        """)
        
        # 设置列宽
        header = table_view.horizontalHeader()
        if header:
            header.setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed)  # 关键词列固定宽度
            header.setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)  # 回复内容列自动拉伸
            header.setSectionResizeMode(2, QHeaderView.ResizeMode.Fixed)  # 操作列固定宽度
        
        table_view.setColumnWidth(0, 120)  # 关键词列宽度
        table_view.setColumnWidth(2, 50)   # 操作列宽度
        
        # 设置表格行为
        table_view.setSelectionBehavior(QTableView.SelectionBehavior.SelectRows)
        table_view.setAlternatingRowColors(True)
        if table_view.verticalHeader():
            table_view.verticalHeader().setVisible(False)  # 隐藏行号
        
        layout.addWidget(table_view)
        
        parent_layout.addWidget(group)


    def load_config(self):
        """从配置数据加载到UI字段"""


        try:
            # 年龄限制
            if 'limitAge' in self.config_data:
                self.ui_fields['age_enabled'].setChecked(self.config_data['limitAge'])
            if 'limitAgeText' in self.config_data:
                age_data = self.config_data['limitAgeText']
                self.ui_fields['age_min'].setText(str(age_data.get('start', '25')))
                self.ui_fields['age_max'].setText(str(age_data.get('end', '45')))
            
            # 性别限制
            if 'limitSex' in self.config_data:
                self.ui_fields['gender_enabled'].setChecked(self.config_data['limitSex'])
            if 'limitSexText' in self.config_data:
                sex_text = self.config_data['limitSexText']
                self.ui_fields['gender_male'].setChecked('男' in sex_text)
                self.ui_fields['gender_female'].setChecked('女' in sex_text)
            
            # 学历限制
            if 'limitXl' in self.config_data:
                self.ui_fields['education_enabled'].setChecked(self.config_data['limitXl'])
            if 'limitXlList' in self.config_data:
                xl_list = self.config_data['limitXlList']
                education_mapping = {
                    '初中': 'education_初中',
                    '中专': 'education_中专_中技',
                    '大专': 'education_大专',
                    '本科': 'education_本科',
                    '硕士': 'education_硕士',
                    '博士': 'education_博士',
                    '全日制': 'education_全日制'
                }
                for xl in xl_list:
                    field_name = education_mapping.get(xl)
                    if field_name and field_name in self.ui_fields:
                        self.ui_fields[field_name].setChecked(True)
            
            # 过滤关键词
            if 'filterPeople' in self.config_data:
                self.ui_fields['filter_keywords_enabled'].setChecked(self.config_data['filterPeople'])
            if 'filterPeopleText' in self.config_data:
                self.ui_fields['filter_keywords'].setText(self.config_data['filterPeopleText'])
            
            # 自动回复设置
            if 'pass' in self.config_data:
                pass_data = self.config_data['pass']
                self.ui_fields['auto_reply_年龄'].setPlainText(pass_data.get('age', ''))
                self.ui_fields['auto_reply_性别'].setPlainText(pass_data.get('sex', ''))
                self.ui_fields['auto_reply_学历'].setPlainText(pass_data.get('xl', ''))
                self.ui_fields['auto_reply_过滤'].setPlainText(pass_data.get('filter', ''))
            
            # 筛选与交换设置
            if 'changeWechat' in self.config_data:
                self.ui_fields['exchange_微信'].setChecked(self.config_data['changeWechat'])
            if 'changePhone' in self.config_data:
                self.ui_fields['exchange_手机'].setChecked(self.config_data['changePhone'])
            if 'filterVirtual' in self.config_data:
                self.ui_fields['filter_虚拟号码'].setChecked(self.config_data['filterVirtual'])
            if 'filterCompose' in self.config_data:
                self.ui_fields['filter_同事已聊'].setChecked(self.config_data['filterCompose'])
            if 'timeClean' in self.config_data:
                self.ui_fields['timer_释放内存'].setChecked(self.config_data['timeClean'])
            if 'noChat' in self.config_data:
                self.ui_fields['no_chat_职位'].setChecked(self.config_data['noChat'])
            if 'noChatText' in self.config_data:
                self.ui_fields['no_chat_position_days'].setText(str(self.config_data.get('noChatText', '25')))
            
            # 随机问候语
            self.ui_fields['random1'].setText(self.config_data.get('random1', ''))
            self.ui_fields['random2'].setText(self.config_data.get('random2', ''))
            self.ui_fields['random3'].setText(self.config_data.get('random3', ''))
            
            # 关键词回复
            if 'keyword' in self.config_data:
                keyword_data = self.config_data['keyword']
                table_model = self.ui_fields['keyword_reply_table']
                table_model._data = [[item['key'], item['value']] for item in keyword_data]
                table_model.layoutChanged.emit()
                
        except Exception as e:
            print(f"加载配置时出错: {e}")
    
    def save_config(self):
        """保存配置到新的JSON格式并打印"""
        try:
            config = {
                "tableName": "gt",
                "changeWechat": self.ui_fields['exchange_微信'].isChecked(),
                "changePhone": self.ui_fields['exchange_手机'].isChecked(),
                "pass": {
                    "age": self.ui_fields['auto_reply_年龄'].toPlainText(),
                    "sex": self.ui_fields['auto_reply_性别'].toPlainText(),
                    "xl": self.ui_fields['auto_reply_学历'].toPlainText(),
                    "filter": self.ui_fields['auto_reply_过滤'].toPlainText()
                },
                "speed": {
                    "Start1": 5,
                    "End1": 8,
                    "Start2": 10,
                    "End2": 12,
                    "Start3": 10,
                    "End3": 12
                },
                "zw": [],
                "keyword": [
                    {
                        "key": row[0],
                        "value": row[1]
                    }
                    for row in self.ui_fields['keyword_reply_table']._data
                ],
                "filterVirtual": self.ui_fields['filter_虚拟号码'].isChecked(),
                "filterCompose": self.ui_fields['filter_同事已聊'].isChecked(),
                "timeClean": self.ui_fields['timer_释放内存'].isChecked(),
                "noChat": self.ui_fields['no_chat_职位'].isChecked(),
                "noChatText": self.ui_fields['no_chat_position_days'].text(),
                "limitAge": self.ui_fields['age_enabled'].isChecked(),
                "limitAgeText": {
                    "start": self.ui_fields['age_min'].text(),
                    "end": self.ui_fields['age_max'].text()
                },
                "limitSex": self.ui_fields['gender_enabled'].isChecked(),
                "limitSexText": self._get_selected_gender(),
                "limitXl": self.ui_fields['education_enabled'].isChecked(),
                "limitXlList": self._get_selected_education(),
                "filterPeople": self.ui_fields['filter_keywords_enabled'].isChecked(),
                "filterPeopleText": self.ui_fields['filter_keywords'].text(),
                "random1": self.ui_fields['random1'].text(),
                "random2": self.ui_fields['random2'].text(),
                "random3": self.ui_fields['random3'].text()
            }
            
            # 更新内部配置数据
            self.config_data = config
            config_manager.save_config(self.config_filename, self.config_data)
            print(f"配置已保存到: {config_manager.get_config_path(self.config_filename)}")
            return config
            
        except Exception as e:
            print(f"保存配置时出错: {e}")
            return None

    def _get_selected_gender(self):
        """获取选中的性别"""
        selected = []
        if self.ui_fields['gender_male'].isChecked():
            selected.append('男')
        if self.ui_fields['gender_female'].isChecked():
            selected.append('女')
        return ' '.join(selected)

    def _get_selected_education(self):
        """获取选中的学历列表"""
        education_mapping = {
            'education_初中': '初中',
            'education_中专_中技': '中专',
            'education_大专': '大专',
            'education_本科': '本科',
            'education_硕士': '硕士',
            'education_博士': '博士',
            'education_全日制': '全日制'
        }
        
        selected = []
        for field_name, display_name in education_mapping.items():
            if field_name in self.ui_fields and self.ui_fields[field_name].isChecked():
                selected.append(display_name)
        
        return selected